<?php

namespace Tiger\Component;

use Aliyun\OTS\OTSClient;
use Aliyun\OTS\OTSServerException;
use Tiger\Face\StoreInterFace;

class Ots implements StoreInterFace
{
    private $_conf = null;
    private $_client = null;

    public function __construct($config)
    {
        $this->_conf = $config;
    }

    public function get($table, array $pk, array $columns = array())
    {
        $request = array
        (
            'table_name' => $table,
            'primary_key' => $pk,
        );
        if (!empty($columns))
        {
             $request['columns_to_get'] = $columns;
        }

        $response = null;
        try
        {
            self::getClient();
            $response = $this->_client->getRow($request);
        }
        catch (OTSServerException $e)
        {
            // var_dump($e->getOTSErrorCode());
            // var_dump($e->getOTSErrorMessage());
        }

         //data format
        $result = array();
        foreach ($response['row']['attribute_columns'] as $key => $value)
        {
            $result[$key] = gzuncompress(base64_decode($value));
            $decode = @json_decode($result[$key], true);
            if ($decode)
            {
                $request[$key] = $decode;
            }
        }
        return $result;
    }

    public function put($table, array $pk, array $data)
    {
        //data format
        foreach ($data as $key => $value)
        {
            $value = is_array($value) ? json_encode($value) : $value;
            $data[$key] = base64_encode(gzcompress($value, 5));
        }
        self::getClient();

        $request = array
        (
            'table_name' => $table,
            // condition可以为IGNORE, EXPECT_EXIST, EXPECT_NOT_EXIST
            'condition' => 'IGNORE',
            'primary_key' => $pk,
            'attribute_columns_to_put' => $data,
        );
        $response = $this->_client->updateRow($request);
        if (is_array($response) && 0 < $response['consumed']['capacity_unit']['write'])
        {
            return true;
        }
        return false;
    }

    private function getClient()
    {
        if (is_null($this->_client))
        {
            $this->_client = new OTSClient($this->_conf);
            $this->_client->getClientConfig()->debugLogHandler = null;
            $this->_client->getClientConfig()->errorLogHandler = null;
        }
        return true;
    }
}
